//
//  LYVideoPlayBackView.m
//  LYLiveApp
//
//  Created by QD on 2018/6/26.
//  Copyright © 2018年 览益信息科技. All rights reserved.
//

#import "LYVideoPlayBackView.h"
#import <MediaPlayer/MPMoviePlayerController.h>
#import <AVFoundation/AVFoundation.h>
#import "VHallApi.h"
#import "LYCustomSlider.h"
#import "LYPlaybackModel.h"
#import "LYVideoNoDataView.h"

@interface LYVideoPlayBackView ()<VHallMoviePlayerDelegate>
@property(nonatomic,strong) UIButton *centerPlayButton;
@property(nonatomic,strong) UIButton *rePlayButton;
@property (strong, nonatomic) UIImageView *coverImage;
@property(nonatomic,strong) UIButton *backButton;
@property (weak, nonatomic) IBOutlet LYCustomSlider *progressSlider;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property(nonatomic,strong) VHallMoviePlayer *moviePlayer;
@property(nonatomic,strong) MPMoviePlayerController * hlsMoviePlayer;
@property(nonatomic,strong) LYPlaybackModel *playModel;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property(nonatomic,strong) NSTimer *progressTimer;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property(nonatomic,strong) LYVideoNoDataView *noVideoView;

@end

@implementation LYVideoPlayBackView

+ (instancetype)viewWithXib
{
    LYVideoPlayBackView *view = [[[UINib nibWithNibName:@"LYVideoPlayBackView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    return view;
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    [self registerLiveNotification];
    
    [self addSubview:self.centerPlayButton];
    [self addSubview:self.rePlayButton];
    [self addSubview:self.coverImage];
   
    self.progressSlider.layer.cornerRadius = 2.5;
    self.progressSlider.layer.masksToBounds = YES;
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"video_slider"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(_processChange:) forControlEvents:UIControlEventValueChanged];

    NSInteger width = SCREEN_WIDTH;
    NSString *imgUrl = nil; // [NSString stringWithFormat:@"%@?imageView2/3/w/%ld/h/211",self.playModel.img_url,width];
    [self.coverImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
    [self insertSubview:self.centerPlayButton aboveSubview:self.coverImage];
    [self insertSubview:self.navView aboveSubview:self.coverImage];
    self.coverImage.frame = self.bounds;
    
    self.centerPlayButton.hidden = NO;
    
    _moviePlayer = [[VHallMoviePlayer alloc] initWithDelegate:self];
    self.hlsMoviePlayer =[[MPMoviePlayerController alloc] init];
    self.hlsMoviePlayer.controlStyle = MPMovieControlStyleNone;
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer.view setFrame:self.bounds];
    self.hlsMoviePlayer.shouldAutoplay= YES;
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_moviePlayerViewTap)];
//    self.overView.userInteractionEnabled = YES;
//    [self.overView addGestureRecognizer:tap];
    
    //播放器
    _hlsMoviePlayer.view.frame = CGRectMake(0, 0, self.frame.size.width, self.height);//self.view.bounds;
    [self addSubview:self.hlsMoviePlayer.view];
    [self sendSubviewToBack:self.hlsMoviePlayer.view];
}

- (void)_processChange:(UISlider *)slider {
    
    [self.hlsMoviePlayer pause];
    [self.hlsMoviePlayer setCurrentPlaybackTime:(slider.value * self.hlsMoviePlayer.duration)];
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer play];
}

//注册通知
- (void)registerLiveNotification
{
    
//    [self.view addObserver:self forKeyPath:kViewFramePath options:NSKeyValueObservingOptionNew context:nil];
   
    //已经进入活跃状态的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive)name:UIApplicationDidBecomeActiveNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground)name:UIApplicationDidEnterBackgroundNotification object:nil];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.hlsMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.hlsMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayeExitFullScreen:) name:MPMoviePlayerDidExitFullscreenNotification object:self.hlsMoviePlayer];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_orientationChanged) name:@"UIDeviceOrientationDidChangeNotification"object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.hlsMoviePlayer];
}



#pragma mark - VHMoviePlayerDelegate
- (void)playError:(LivePlayErrorType)livePlayErrorType info:(NSDictionary *)info;
{
    
    [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
    NSString * msg = @"";
    switch (livePlayErrorType) {
        case kLivePlayParamError:
        {
            msg = @"参数错误";
            LYLog(@"%@",msg);
            [self _handleErrorAction];
        }
            break;
        case kLivePlayRecvError:
        {
            msg = @"对方已经停止直播";
            LYLog(@"%@",msg);
            [self _handleErrorAction];
            
        }
            break;
        case kLivePlayCDNConnectError:
        {
            msg = @"服务器任性...连接失败";
            LYLog(@"%@",msg);
            [self _handleErrorAction];
            
        }
            break;
        case kLivePlayGetUrlError:
        {
            msg = @"获取服务器地址报错";
            LYLog(@"%@",info[@"content"]);
            [self _handleErrorAction];
            
        }
            break;
        default:
            break;
    }
}

-(void)VideoPlayMode:(VHallMovieVideoPlayMode)playMode isVrVideo:(BOOL)isVrVideo
{
    LYLog(@"---%ld",(long)playMode);
    switch (playMode) {
        case VHallMovieVideoPlayModeNone:
        case VHallMovieVideoPlayModeMedia:
            
            break;
        case VHallMovieVideoPlayModeTextAndVoice:
        {
        }
            
            break;
            
        case VHallMovieVideoPlayModeTextAndMedia:
            
            break;
        default:
            break;
    }
}

-(void)ActiveState:(VHallMovieActiveState)activeState
{
    LYLog(@"activeState-%ld",(long)activeState);
}

- (void)moviePlaybackStateDidChange:(NSNotification *)note
{
    switch (self.hlsMoviePlayer.playbackState)
    {
        case MPMoviePlaybackStatePlaying:
        {
            LYLog(@"播放");
            self.centerPlayButton.hidden = YES;
            self.playButton.selected = NO;
//            self.fullOverView.playButton.selected = NO;
            self.rePlayButton.hidden = YES;
        }
            break;
        case MPMoviePlaybackStateSeekingBackward:
        case MPMoviePlaybackStateSeekingForward:
        {
            LYLog(@"快进－－快退");
        }
            break;
        case MPMoviePlaybackStateInterrupted:
        {
            LYLog(@"中断了");
        }
            break;
        case MPMoviePlaybackStatePaused:
        {
            LYLog(@"暂停");
            self.centerPlayButton.hidden = NO;
            self.rePlayButton.hidden = YES;
            self.playButton.selected = YES;
//            self.fullOverView.playButton.selected = YES;
            
            if (self.hlsMoviePlayer.view) {
                [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
            }
        }
            break;
        case MPMoviePlaybackStateStopped:
        {
            LYLog(@"停止播放");
            if (self.hlsMoviePlayer.view) {
                [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
            }
        }
            break;
        default:
            break;
    }
}

- (void)movieLoadStateDidChange:(NSNotification *)note
{
    if (self.hlsMoviePlayer.loadState == MPMovieLoadStatePlayable)
    {
        if (self.hlsMoviePlayer.view) {
            [LYUtil showProgressHUDAddedToVideoView:self.hlsMoviePlayer.view];
        }
        LYLog(@"开始加载加载");
    }else if(self.hlsMoviePlayer.loadState == (MPMovieLoadStatePlaythroughOK|MPMovieLoadStatePlayable))
    {
        if (self.hlsMoviePlayer.view) {
            [LYUtil hideHUDTo:self.hlsMoviePlayer.view];
        }
        self.coverImage.hidden = YES;
//        self.isError = NO;
        [self.noVideoView removeFromSuperview];
        LYLog(@"加载完成");
        [self _resetProgressTimer];
        self.playButton.selected = NO;
        self.centerPlayButton.hidden = YES;
    }
}

-(void)moviePlayeExitFullScreen:(NSNotification*)note
{
    
}

- (void)moviePlaybackDidFinish:(NSNotification *)note {
    
    [self _stopProgressTimer];
    self.progressSlider.value = 0;
//    self.fullOverView.fullProgressSlider.value = 0;
    self.playButton.selected = YES;
    self.rePlayButton.hidden = NO;
    self.centerPlayButton.hidden = YES;
    self.rePlayButton.center = CGPointMake(self.centerX,self.centerY);
}

- (void)_handleErrorAction {
    WS(weakSelf)
//    self.isError = YES;
    self.rePlayButton.hidden = YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.hlsMoviePlayer pause];
        [LYUtil hideHUDTo:weakSelf.hlsMoviePlayer.view];
        [LYUtil hideHUDTo:weakSelf.coverImage];
        weakSelf.coverImage.hidden = YES;
        weakSelf.centerPlayButton.hidden = YES;
        [weakSelf addSubview:weakSelf.noVideoView];
       
//        [weakSelf insertSubview:weakSelf.noVideoView aboveSubview:weakSelf.overView];
        [weakSelf insertSubview:weakSelf.navView aboveSubview:weakSelf.noVideoView];
        weakSelf.noVideoView.frame = weakSelf.hlsMoviePlayer.view.bounds;
        weakSelf.noVideoView.center = weakSelf.hlsMoviePlayer.view.center;
        weakSelf.hlsMoviePlayer.view.backgroundColor = RGB(155, 155, 155);
//        if (!weakSelf.isFullScreen) {
//            weakSelf.noVideoView.backButton.hidden = NO;
//        }
    });
}

- (void)_resetProgressTimer {
    if (nil ==_progressTimer) {
        _progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                          target:self
                                                        selector:@selector(_updateProgress)
                                                        userInfo:nil
                                                         repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.progressTimer.fireDate timeIntervalSinceNow]) < 1.0)
            [self.progressTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    }
}

- (void)_stopProgressTimer {
    if (self.progressTimer) {
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
}

- (void)_updateProgress {
    
    NSString *currentTime = [NSString stringWithFormat:@"%f",self.hlsMoviePlayer.currentPlaybackTime];
    NSString *totalTime = [NSString stringWithFormat:@"%f",self.hlsMoviePlayer.duration];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self getMMSSFromSS:currentTime],[self getMMSSFromSS:totalTime]];
    self.progressSlider.value = self.hlsMoviePlayer.currentPlaybackTime/self.hlsMoviePlayer.duration;
//    if (self.fullOverView.fullTimeLabel && self.fullOverView.fullProgressSlider) {
//        self.fullOverView.fullTimeLabel.text = self.timeLabel.text;
//        self.fullOverView.fullProgressSlider.value = self.progressSlider.value;
//    }
}

-(NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    NSString *format_time;
    if (seconds/3600 == 0) {
        format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    } else {
        format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    }
    return format_time;
}


- (void)_startPlayer {
    
    if (self.hlsMoviePlayer.view) {
        [LYUtil showProgressHUDAddedToVideoView:self.coverImage];
    }
    self.hlsMoviePlayer.view.backgroundColor = [UIColor colorWithHexString:@"#333333"];
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
    self.playModel.vurl = @"522193684";
    param[@"id"] = self.playModel.vurl;
    param[@"name"] = [UIDevice currentDevice].name;
    param[@"email"] = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [_moviePlayer startPlayback:param moviePlayer:self.hlsMoviePlayer];
}

- (void)playVideo {
    
    [self _startPlayer];
    [self.hlsMoviePlayer prepareToPlay];
    [self.hlsMoviePlayer play];
}


#pragma mark ----- getters and setters
- (UIButton *)centerPlayButton {
    
    if (nil == _centerPlayButton) {
        _centerPlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _centerPlayButton.frame = CGRectMake(SCREEN_WIDTH/2- 25,self.size.height/2-25 , 50, 50);
        [_centerPlayButton setImage:[UIImage imageNamed:@"playblack_centerPlay"] forState:UIControlStateNormal];
        _centerPlayButton.hidden = YES;
        [_centerPlayButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _centerPlayButton;
}

- (UIButton *)rePlayButton {
    
    if (nil == _rePlayButton) {
        _rePlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rePlayButton.frame = CGRectMake(self.hlsMoviePlayer.view.centerX, self.hlsMoviePlayer.view.centerY, 56, 72);
        [_rePlayButton setImage:[UIImage imageNamed:@"playblack_replay"] forState:UIControlStateNormal];
        [_rePlayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _rePlayButton.hidden = YES;
        [_rePlayButton addTarget:self action:@selector(replayVideo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rePlayButton;
}

- (UIImageView *)coverImage {
    
    if (nil == _coverImage) {
        _coverImage = [[UIImageView alloc] initWithFrame:self.bounds];
        _coverImage.backgroundColor = RGB(155, 155, 155);
        _coverImage.contentMode = UIViewContentModeScaleAspectFill;
        _coverImage.clipsToBounds = YES;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(10, 30, 40, 40);
        [button setImage:[UIImage imageNamed:@"video_full_back"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        [_coverImage addSubview:button];
        self.backButton = button;
    }
    return _coverImage;
}

- (LYVideoNoDataView *)noVideoView {
    WS(weakSelf)
    if (nil == _noVideoView) {
        _noVideoView = [LYVideoNoDataView viewWithXib];
        _noVideoView.refreshBlock = ^() {
            [weakSelf _startPlayer];
            [weakSelf.noVideoView removeFromSuperview];
        };
        
        _noVideoView.backBlock = ^{
//            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _noVideoView;
}



@end
